'''
Created on Nov 8, 2011

@author: robert
'''
import subprocess
import Database.Database as DB
import Database.DbFunctions as DBF
import ftplib

#Start DB connection
conn = DB.databaseGetConn()
cursor = DB.getCursorFromConn(conn)

#Hard-Coded variables (for now)
location_id ='0'
user_id = '2'
scanner_id = '2'

artifact_id = None
name = None
command = None
ir_reflectance = 0

current_front_id = 0
current_back_id = 0

imageFileArray = []

#Archives letter naming convention
letter_offset = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

def captureAndDownloadImage(filename):
    #Autodetect the camera and take a photo
    subprocess.call(["gphoto2", "--auto-detect"])
    subprocess.call(["gphoto2", "--capture-image-and-download", "--filename=" + filename])
'''
def commitToDB():
    conn.ping(True)
    cursor = DB.getCursorFromConn(conn)
    next_i = DBF.getNextNumForLocation(cursor, location_id)
    base_name = DBF.getBaseNameForLocation(cursor, location_id)
    print "Base Name: " + base_name + " and next_i: " + str(next_i)
'''
def newFolderPrompt():
    #Need to grab the last ~10 or so folders from the database
    #give the user a prompt to select between them and also the ability
    #to create a new folder
    
    #Once selected, the location_id needs to be updated so that all
    #future operations will correspond to the correct location
    
    #This will ensure consistent image naming
    locationPresent = 0
    folderHash = DBF.getRecentFolders(cursor)
    
    while locationPresent == 0:
        for folder in folderHash:
            print "Location_ID: %s, room: %s, case_number: %s, shelf_number: %s, box_number: %s, folder_name: %s" % (folder['location_id'], folder['room'], folder['case_num'], folder['shelf_num'], folder['box_num'], folder['folder_name'])
        
        location_id = raw_input("Please enter the number of the folder you would like you use\nIf you would like to create a new folder, enter '-1': ")
        print "LOCATION ID: %s" % location_id
        
        for folder in folderHash:
            if int(folder['location_id']) == int(location_id) or int(location_id) == -1:
                locationPresent = 1
    
    #Have a valid location_id or -1 (indicates a new folder)
    if int(location_id) == -1:
        con = 0
        while con == 0:
            #prompt for necessary fields
            room = raw_input("Please enter the folder's room: ")
            caseNum = raw_input("Please enter the folder's case number: ")
            shelfNum = raw_input("Please enter the folder's shelf number: ")
            boxNum = raw_input("Please enter the folder's box number: ")
            folderName = raw_input("Please enter the folder's name: ")
            
            con = raw_input("Does this look right?\nLocation_ID: %s, room: %s, case_number: %s, shelf_number: %s, box_number: %s, folder_name: %s\n 1-Yes, 0-No" % (folder['location_id'] + 1, room, caseNum, shelfNum, boxNum, folderName))
        
        location_id = DBF.createNewFolder(conn, cursor, room, caseNum, shelfNum, boxNum, folderName)
        print "Set a new location id of: " + str(location_id)
        conn.commit()
    return location_id

def uploadImageToServer(batchFilePath, imageFileArray):
    #using system calls, send this file to the ec2 server
    batchFile = open(batchFilePath, "w")
    
    for file in imageFileArray:
        batchFile.write("put " + file + "\n")
    batchFile.close()
    
    subprocess.call(["sftp", "-b", batchFilePath, "-o", "IdentityFile=/home/robert/Downloads/tomskey.pem", "ubuntu@107.20.137.103"])

    print "Added files to batch file!"
    #subprocess.call(["echo", "'" + imageFileArray + "'", ">>", batchFilePath])
    
    
while command != "q":
    #take in input
    command = raw_input("Please enter a command (l - lists all commands):")
    
    if command == "f":
        location_id = newFolderPrompt()
    elif command == "l":
        print "\tf - Change Folder\n\tq - Quit\n\ti - Capture Images\n\ta - New Artifact\n\ts - Capture and Create in Sequence"
    elif command == "c":
        captureAndDownloadImage()
    elif command == "a":
        print "OK, BEFORE ART CREATION LOC: " + location_id
        if location_id == 0:
            print "NO LOCATION ID"
            continue
        next_i = DBF.getNextNumForLocation(cursor, str(location_id))
        base_name = DBF.getBaseNameForLocation(cursor, str(location_id))
        
        #Make name with index attached
        name = "%s_%s" % (base_name, next_i)
        artifact_id = DBF.makeNewArtifact(conn, cursor, str(location_id), next_i, base_name, user_id, ir_reflectance)
        conn.commit()
        current_back_id = 0
        print "New artifact #" + str(artifact_id) + " was created successfully!"
    elif command == "b":
        #Upload all the images that have been collected in this round
        fileArray = ["/home/robert/Downloads/tomskey2", "/home/robert/Downloads/tomskey.pem"]
        uploadImageToServer("/home/robert/batch", imageFileArray)
    elif command == "i":
        #check to make sure we have a valid artifact
        if artifact_id == None:
            print "Make sure there is a valid artifact before adding an image\n"
        else:
            imageOrientation = 0
            
           # while imageOrientation != 1 and imageOrientation != 2:
            #Grab the image orientation
            imageOrientation = raw_input("Front: 1, Back: 2 :")
            
            #if front of image
            if imageOrientation == "1":
                captureAndDownloadImage(name)
                raw_path = "raw_scans\\\%s" % (name)
                print "Raw_FRONT_PATH: " + raw_path
                DBF.addImageToArtifact(conn, cursor, artifact_id, name,
                                        raw_path, user_id, imageOrientation, user_id)
                conn.commit()
                actualPath = "/home/robert/workspace/ESDA/src/trunk/src/Gado/" + name
                imageFileArray.append(actualPath)
                #uploadImageToServer(name)
                
            elif imageOrientation == "2":
                captureAndDownloadImage(name + letter_offset[current_back_id])
                raw_path = "raw_scans\\\%s" % (name + letter_offset[current_back_id])
                #Actual path - MAKE THIS CORRECT!!!
                actualPath = "/home/robert/workspace/ESDA/src/trunk/src/Gado/" + name + letter_offset[current_back_id]
                print "Raw_BACK_PATH: " + raw_path
                DBF.addImageToArtifact(conn, cursor, artifact_id, name + letter_offset[current_back_id],
                                       raw_path, user_id, imageOrientation, user_id)
                conn.commit()
                imageFileArray.append(actualPath)
                #uploadImageToServer(name + letter_offset[current_back_id])
                current_back_id += 1
    elif command == "s":
        while command != "q":
            if location_id == 0:
                print "NO LOCATION ID"
                break
            next_i = DBF.getNextNumForLocation(cursor, str(location_id))
            base_name = DBF.getBaseNameForLocation(cursor, str(location_id))
        
            #Make name with index attached
            name = "%s_%s" % (base_name, next_i)
            artifact_id = DBF.makeNewArtifact(conn, cursor, str(location_id), next_i, base_name, user_id, ir_reflectance)
            conn.commit()
            current_back_id = 0
            print "New artifact #" + str(artifact_id) + " was created successfully!"
            go = raw_input("Take picture of FRONT. Hit enter to go")
                        
            captureAndDownloadImage(name)
            raw_path = "raw_scans\\\%s" % (name)
            print "Raw_FRONT_PATH: " + raw_path
            DBF.addImageToArtifact(conn, cursor, artifact_id, name, raw_path, user_id, "1", user_id)
            conn.commit()
            actualPath = "/home/robert/workspace/ESDA/src/trunk/src/Gado/" + name
            imageFileArray.append(actualPath)
            #uploadImageToServer(name)
            go = ""
            while go != "n":
                go = raw_input("Take picture of BACK? Enter to continue, n to move to next aftifact, q to quit")
                if go == "q":
                     command = "q"
                     break
                if go != "n":
                    captureAndDownloadImage(name + letter_offset[current_back_id])
                    raw_path = "raw_scans\\\%s" % (name + letter_offset[current_back_id])
                    #Actual path - MAKE THIS CORRECT!!!
                    actualPath = "/home/robert/workspace/ESDA/src/trunk/src/Gado/" + name + letter_offset[current_back_id]
                    print "Raw_BACK_PATH: " + raw_path
                    DBF.addImageToArtifact(conn, cursor, artifact_id, name + letter_offset[current_back_id], raw_path, user_id, "2",user_id)
                    conn.commit()
                    imageFileArray.append(actualPath)
                    #uploadImageToServer(name + letter_offset[current_back_id])
                    current_back_id += 1
            
cursor.close()
'''name = "%s_%s" % (base_name, next_i)
image_name = "%s.tiff" % name
raw_path = "C:\\to_transfer\\%s" % image_name
print raw_path
os.rename('TWAIN.tmp', raw_path)
raw_path = "raw_scans\\\%s" % image_name
artifact_id = DBF.makeNewArtifact(conn, cursor, location_id, next_i, base_name, user_id, 0)
DBF.addImageToArtifact(conn, cursor, artifact_id, name, raw_path, scanner_id, '1', user_id)
conn.commit()'''
